//表格编辑器：可以忽略
function remove_item(id) {
    $("#id-" + id.toString()).remove()
}
function add_item() {
    var nxt_id = String(Number($("tr:last").prop("id").substring(3)) + 1);
    var html = "<tr id='id-" + nxt_id + "'>";
    get_fields().forEach(function () {
        html += '<td><input type="text" class="form-control te-item"/></td>'
    });
    $("tr:last").after(html + '<td><a href="javascript:remove_item(' + nxt_id + ')" class="btn btn-danger btn-sm">删除</a></td></tr>');
}

function get_fields() {
    var ret = [];
    $(".te-field").each(function () { ret.push($(this).text()); });
    return ret;
}
function get_data() {
    var fields = get_fields(), n_fields = fields.length;
    var ret = [], i = 1, itm = {};
    $(".te-item").each(function () {
        itm[fields[(i - 1) % n_fields]] = $(this).val();
        if (i % n_fields === 0) {
            ret.push(itm);
            itm = {};
        }
        i += 1;
    });
    return ret;
}
function set_tip(success, content) {
    target = "#te_tip"
    if (success === true) {
        $(target).removeClass("text-danger").addClass("text-success")
    } else {
        $(target).addClass("text-danger").removeClass("text-success")
    }
    $(target).text(content)
    $(target).show()
}
function editor_save(target, title) {
    $.ajax({
        async: true, cache: false, type: 'POST', url: '/api/' + target, data: { "json": JSON.stringify(get_data()) },
        success: function (data) {
            if (data.success === true) {
                set_tip(true, title + "设置成功。");
            } else {
                set_tip(false, title + "设置失败！");
            }
        },
        error: function (err) {
            set_tip(false, title + "设置失败！");
        }
    });
}